package com.sc.fs3.controller;


import com.sc.fs3.pojo.FileEntity;
import com.sc.fs3.repository.DocRepository;
import com.sc.fs3.service.FileExtractService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 文件上传
 */
@RestController
@RequestMapping("/file")
public class FileUploadController {
    private Logger log = LoggerFactory.getLogger(FileUploadController.class);
    //时间格式化
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

    @Autowired
    private FileExtractService fileExtractService;         //文本提取

    @Resource
    private DocRepository docRepository;   //es api

    /**
     * 上传文件
     * @param request
     * @return
     */
    @RequestMapping("/upload")
    public String uploadFile(MultipartFile[] files, HttpServletRequest request){
        int indexing = 0;   //成功索引的文件数
        int saved = 0;      //成功存储的文件数
        for(int i=0;i<files.length;i++) {
            FileEntity fileEntity = new FileEntity();
            fileEntity.setId(UUID.randomUUID().toString());     // 随机生成UUID
            fileEntity.setTitle(files[i].getOriginalFilename());    //文件名
            fileEntity.setSize(files[i].getSize());                 //文件大小
            LocalDateTime dateTime = LocalDateTime.now();       //获取当前时间
            fileEntity.setUploadtime(dateTime);   //上传时间
            try {
                InputStream fis = files[i].getInputStream();
            } catch (IOException e) {
                log.error("文件解析出错");
            }
            //文本提取
            String content = fileExtractService.extractContent(files[i]);   //文件内容
            if("".equals(content)){     //判断空
                content = "-";
            }
            fileEntity.setContent(content);
            log.info("--params: " + fileEntity.toString());
            //全文索引中(存储)
            String indexName = "doc";
            String type = "fileEntity";
            FileEntity entity = docRepository.save(fileEntity);
            System.out.println();
            log.info("成功--： : " + entity);     //如果成功，则返回CREATED
            if (entity!=null ) {
                indexing++;
            }
        }
        return "SUCCESS indexing " + indexing ;
    }
}
